# !encoding=utf-8

import sys
import json
import time

from GPIO import GPIO
from socketserver import DatagramRequestHandler
import socketserver


class Led(object):
    def __init__(self, idx):
        self.idx = idx
        self.gpio = GPIO(idx, init_with_output=True)

    def turn_on(self):
        self.gpio.high()

    def turn_off(self):
        self.gpio.low()


class SteerLedService(DatagramRequestHandler):
    leds = list()

    @classmethod
    def set_leds(cls, idxes):
        for idx in idxes:
            SteerLedService.leds.append(Led(idx))

    @classmethod
    def light_on(cls):
        for led in SteerLedService.leds:
            led.turn_on()

    @classmethod
    def light_off(cls):
        for led in SteerLedService.leds:
            led.turn_off()

    @classmethod
    def flash(cls, interval_seconds=1, time_seconds=10):
        while time_seconds > 0:
            for led in SteerLedService.leds:
                led.turn_on()
            time.sleep(interval_seconds)

            for led in SteerLedService.leds:
                led.turn_off()
            time.sleep(interval_seconds)
            time_seconds -= interval_seconds * 2

    def handle(self):
        data = self.rfile.read()
        req_json = json.loads(data)
        action = req_json.get("action", None)
        if action is not None:
            if action == "turn-on-light":
                pass
            elif action == "flash-light":
                pass

    @classmethod
    def run(cls, port):
        server = socketserver.ThreadingUDPServer(('127.0.0.1', port), SteerLedService)
        server.serve_forever()


def main(port):
    SteerLedService.set_leds([17, 22, 27])
    SteerLedService.run(port)


if __name__ == "__main__":
    main(int(sys.argv[1]))
